package com.nuo.backend.modules.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nuo.backend.common.exception.GlobalException;
import com.nuo.backend.modules.security.service.SecCaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: TODO 用户名密码过滤器
 * @author nuo
 * @date 2022/12/5 23:08
 * @version 1.0
 */
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private SessionRegistry sessionRegistry;

    @Autowired
    private SecCaptchaService secCaptchaService;

    //TODO form-data 格式的登录注册
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        // 判断数据是否为json类型
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)
                || request.getContentType().contains("application/json")) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            Map<String,String> formData = new HashMap<>(16);
            try  {
                formData = mapper.readValue(request.getReader(), Map.class);

                log.info("po.{}: " + formData.get(getUsernameParameter()), getUsernameParameter());
                log.info("po.{}: " + formData.get(getPasswordParameter()), getPasswordParameter());

                authRequest = new UsernamePasswordAuthenticationToken(formData.get(getUsernameParameter()), formData.get(getPasswordParameter()));

            } catch (IOException e) {
                log.error(e.getMessage());
                authRequest = new UsernamePasswordAuthenticationToken("", "");
            } finally {

                // TODO 校验验证码
                // checkCode(formData.get("uuid"), formData.get("code"), request);

                setDetails(request, authRequest);

                // 配置单方登陆 session
                AccountUser principal = new AccountUser();
                principal.setUsername(formData.get(getUsernameParameter()));
                sessionRegistry.registerNewSession(request.getSession(true).getId(), principal);

                return this.getAuthenticationManager().authenticate(authRequest);
            }
        } else {

            // checkCode(request.getParameter("uuid"), request.getParameter("code"), request);

            return super.attemptAuthentication(request, response);
        }
    }

    private void checkCode(String uuid, String code, HttpServletRequest request) {

        log.info("uuid: " + uuid);
        log.info("code: " + code);

        // TODO session
        if (request.getSession().getAttribute("code") == null || !((String) request.getSession().getAttribute("code")).equalsIgnoreCase(code)) {
            throw new AuthenticationException("验证码输入有误..."){};
        }

        log.info("req.session.code: " + request.getSession().getAttribute("code"));

        request.getSession().removeAttribute("code");

        // TODO Redis & MySQL
        if (!secCaptchaService.validate(uuid, code)) {
            throw new AuthenticationException("验证码输入有误..."){};
        }

    }

}
